<template>
  <div class="mytabs">
    <a-tabs v-model:activeKey="activeKey" @tab-click="handleChange" type="editable-card">
      <a-tab-pane :key="item.key" :tab="item.name" v-for="item in props.tabsList" />
      <template #addIcon>
        <SvgIcon @click="handleAdd" class="iconDef" :name="'addPush'" :color="'#586371'" width="16" height="16" />
      </template>
      <template #rightExtra>
        <div class="title-manage" @click="handleLabelManage">
          <SvgIcon class="iconDef" :name="'biaoqian'" :color="'#586371'" width="16" height="16" />
          <div class="label-manage">标签管理</div>
        </div>
      </template>
      <template #moreIcon>
        <SvgIcon class="iconDef" :name="'shu'" :color="'#586371'" width="16" height="16" />
      </template>
    </a-tabs>
  </div>
  <BasicModal
    ref="showActionModal"
    title="设置分组"
    width="800px"
    @emit-callback-fn="modalCallbackFn"
    :confirmLoading="editGroupManagementLoading"
  >
    <template #content>
      <div class="setting-group">
        <div class="setting-group-list">
          <div class="setting-group-box" ref="settingGroupBox">
            <template v-for="(item, index) in groupList">
              <div
                class="setting-group-item"
                :key="item.key"
                v-if="item.name !== '我的收藏夹' || item.type !== 'DEFAULT'"
              >
                <div class="setting-group-item-content">
                  <a-tooltip placement="top">
                    <template #title>
                      <span>删除</span>
                    </template>
                    <SvgIcon
                      class="iconDef"
                      :name="'cutDown'"
                      :color="'#586371'"
                      width="16"
                      height="16"
                      @click="deleteItem(index)"
                    />
                  </a-tooltip>
                  <div class="setting-group-item-name">
                    <span v-if="!item.edit" class="setting-group-item-name-text">{{ item.name }}</span>
                    <a-input
                      v-else
                      class="setting-group-item-name-input"
                      v-model:value="item.name"
                      placeholder="请输入库名"
                      allowClear
                    />
                  </div>
                  <div class="setting-group-item-type">
                    <span v-if="!item.edit" class="setting-group-item-type-text">{{ item.type }}</span>
                    <a-input
                      v-else
                      class="setting-group-item-type-input"
                      v-model:value="item.type"
                      placeholder="请输入库类型"
                      allowClear
                    />
                  </div>
                  <div class="setting-group-item-btn">
                    <template v-if="!item.edit">
                      <a-tooltip placement="top">
                        <template #title>
                          <span>向上排序</span>
                        </template>
                        <SvgIcon
                          class="iconDef"
                          :name="'sort'"
                          :color="'#586371'"
                          width="16"
                          height="16"
                          @click="sortUp(index)"
                        />
                      </a-tooltip>
                      <a-tooltip placement="top">
                        <template #title>
                          <span>编辑</span>
                        </template>
                        <SvgIcon
                          class="iconDef"
                          :name="'edit'"
                          :color="'#586371'"
                          width="16"
                          height="16"
                          @click="item.edit = true"
                        />
                      </a-tooltip>
                    </template>
                    <template v-else>
                      <a-tooltip placement="top">
                        <template #title>
                          <span>完成编辑</span>
                        </template>
                        <SvgIcon
                          class="iconDef"
                          :name="'gougou'"
                          :color="'#586371'"
                          width="16"
                          height="16"
                          @click="completeEditing(item)"
                        />
                      </a-tooltip>
                    </template>
                  </div>
                </div>
              </div>
            </template>
          </div>
          <div class="setting-group-add" @click="settingAddGroup">
            <SvgIcon class="iconDef" :name="'add'" :color="'#2590FF'" width="16" height="16" />
            <span>添加分组</span>
          </div>
        </div>
      </div>
    </template>
  </BasicModal>

  <BasicModal
    ref="showActionTagRef"
    title="标签管理"
    width="400px"
    @emit-callback-fn="confimTagModal"
    :confirmLoading="ediTagManagementLoading"
    class="cusomt-moadl"
  >
    <template #content>
      <div class="color-select">
        <div class="color-list" v-for="(item, index) in tagOptionsList" :key="index">
          <div
            class="color-item"
            :style="{
            background: TagBgColors[item.color as keyof typeof TagBgColors],
            color: TagColors[item.color as keyof typeof TagColors],
          }"
          >
            {{ item.name }}
          </div>
          <a-tooltip placement="top">
            <template #title>
              <span>删除</span>
            </template>
            <SvgIcon
              class="iconDef"
              :name="'chacha'"
              :color="'#778eac'"
              width="16"
              height="16"
              @click="deleteTag(item)"
            />
          </a-tooltip>
        </div>
      </div>
      <div class="add-tag-btn">
        <a-button type="primary" ghost @click="newTagBtn">
          <PlusOutlined />
          新建标签
        </a-button>
      </div>
    </template>
  </BasicModal>

  <BasicModal ref="showAddTagRef" title="新建标签" width="400px" @emit-callback-fn="addCallbackFn">
    <template #content>
      <a-form ref="formTagRef" label-align="right" :model="formTag">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item label="标签名称" name="name" :rules="[{ required: true, message: '请输入标签名称' }]">
              <a-input v-model:value="formTag.name" placeholder="请输入标签名称" allowClear />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item label="标签颜色" name="color" :rules="[{ required: true, message: '请选择标签颜色' }]">
              <div class="color-select-box">
                <div
                  class="color-item"
                  v-for="(value, key, index) in TagColors"
                  @click="formTag.color = key"
                  :key="index"
                  :style="{
                    backgroundColor: value,
                  }"
                >
                  <CheckOutlined v-if="key == formTag.color" style="color: #fff" />
                </div>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
import { PlusOutlined, CheckOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { TagColors, TagBgColors } from '@/enums/commonEnum';
import _ from 'lodash';
import { updataBatchSaveOrUpdateList, updataBatchTagSaveOrList } from '@/api/pipeline';
const props = defineProps({
  tabsList: {
    type: Array<CommonTypes.TabItem>,
    default: () => [],
  },
  tabsValue: {
    type: String,
    default: '',
  },
  tagListData: {
    type: Array,
    default: () => [],
  },
  groupListData: {
    type: Array,
    default: () => [],
  },
});
const emits = defineEmits(['handleChange', 'refreshSelectList']);
const activeKey = ref<string>('');
const showActionModal = ref<any>(null);
const groupList = ref<any[]>([]);

//添加分组
const handleAdd = () => {
  emits('refreshSelectList', false);
  showActionModal.value.showModal();
};

//设置分组
const settingGroupBox = ref<any>(null);
const settingAddGroup = () => {
  const validator = groupList.value.some((v) => {
    return v.name === '' || v.type === '';
  });
  if (validator) {
    message.warning('请输入内容后再添加分组');
    return false;
  }
  groupList.value.forEach((v) => (v.edit = false));
  groupList.value.push({ name: '', type: '', edit: true, sort: groupList.value.length + 1 });
  nextTick(() => {
    settingGroupBox.value.scrollTop = settingGroupBox.value.scrollHeight;
  });
};

const editGroupManagementLoading = ref<boolean>(false);
//分组管理
const modalCallbackFn = async () => {
  const validator = groupList.value.some((v) => {
    return v.name === '' || v.type === '';
  });
  if (validator) {
    message.warning('内容不能为空');
    return false;
  }
  // 修改编辑状态与排序
  editGroupManagementLoading.value = true;
  groupList.value.forEach((item: any, index) => {
    item.edit = false;
    item.sort = index + 1;
  });
  let newItems = groupList.value.map((item) => _.omit(item, ['edit']));
  await updataBatchSaveOrUpdateList(newItems)
    .then(() => {
      message.success('设置成功');
      emits('refreshSelectList');
      showActionModal.value.hideModal();
    })
    .finally(() => {
      editGroupManagementLoading.value = false;
    });
};

const deleteItem = (index: number) => {
  groupList.value.splice(index, 1);
};

const sortUp = (index: number) => {
  if (index === 0) return;
  const temp = groupList.value[index];
  groupList.value[index] = groupList.value[index - 1];
  groupList.value[index - 1] = temp;
};

const completeEditing = (item: any) => {
  if (item.name === '' || item.type === '') {
    message.warning('请输入内容');
    return false;
  }
  item.edit = false;
};

const showActionTagRef = ref<any>(null);
const showAddTagRef = ref<any>(null);
const formTagRef = ref<any>(null);
const formTag = reactive<any>({
  name: '',
  color: '',
});
const newTagBtn = () => {
  formTag.name = '';
  formTag.color = '';
  showAddTagRef.value.showModal();
};

const deleteTag = (item: any) => {
  const index = tagOptionsList.value.findIndex((v) => v.uuid === item.uuid);
  tagOptionsList.value.splice(index, 1);
};

const addCallbackFn = () => {
  formTagRef.value
    .validate()
    .then(() => {
      let objItem = { ...formTag };
      tagOptionsList.value.push(objItem);
      showAddTagRef.value.hideModal();
    })
    .catch((err: any) => {
      console.log('error', err);
    });
};

const tagOptionsList = ref<any[]>([]);

//标签管理
const handleLabelManage = () => {
  emits('refreshSelectList', false);
  showActionTagRef.value.showModal();
};

// 标签选中变化
const handleChange = (key: string) => {
  emits('handleChange', key);
};

const ediTagManagementLoading = ref<boolean>(false);
// 保存标签
const confimTagModal = async () => {
  ediTagManagementLoading.value = true;
  await updataBatchTagSaveOrList(tagOptionsList.value)
    .then(() => {
      message.success('保存成功');
      showActionTagRef.value.hideModal();
      emits('refreshSelectList', false);
    })
    .finally(() => {
      ediTagManagementLoading.value = false;
    });
};
watch(
  () => props.tabsList,
  (newVal: any) => {
    !props.tabsValue && (activeKey.value = newVal[0].key);
  },
  {
    deep: true,
    immediate: true,
  },
);
watch(
  () => props.groupListData,
  (newVal: any) => {
    groupList.value = newVal;
  },
  {
    deep: true,
    immediate: true,
  },
);
watch(
  () => props.tagListData,
  (newVal: any) => {
    tagOptionsList.value = newVal;
  },
  {
    deep: true,
    immediate: true,
  },
);
watch(
  () => props.tabsValue,
  (newVal: any) => {
    activeKey.value = newVal;
  },
  {
    deep: true,
    immediate: true,
  },
);
</script>

<style lang="less" scoped>
.mytabs {
  :deep(.ant-tabs-nav) {
    margin: 0;
  }

  .rightBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-left: 12px;
    .iconDef {
      cursor: pointer;
    }
  }
  :deep(.ant-tabs-tab-remove) {
    display: none;
  }
  :deep(.ant-tabs-tab) {
    border: none;
    background: none;
    padding: 0;
    height: 48px;
    margin-right: 20px;
  }
  :deep(.ant-tabs-ink-bar) {
    visibility: unset;
  }
  :deep(.ant-tabs-nav-add) {
    background: none;
    border: none;
    border-radius: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0;
  }
  :deep(.ant-tabs-nav-more) {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 0 0 12px;
  }
  .title-manage {
    display: flex;
    align-items: center;
    cursor: pointer;
    margin-left: 66px;
    .label-manage {
      margin-left: 8px;
    }
  }
}

.setting-group {
  .setting-group-list {
    width: 100%;
    .setting-group-box {
      width: 100%;
      max-height: 400px;
      overflow-y: auto;
      .setting-group-item {
        width: 100%;
        padding: 10px 0;
        .setting-group-item-content {
          display: flex;
          align-items: center;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.8);
          font-weight: 400;
          .setting-group-item-name {
            flex: 1;
            .setting-group-item-name-text {
              margin-left: 8px;
            }
            .setting-group-item-name-input {
              width: 300px;
              margin-left: 8px;
            }
          }
          .setting-group-item-type {
            flex: 1;
            .setting-group-item-type-text {
              margin-left: 8px;
            }
            .setting-group-item-type-input {
              width: 300px;
              margin-left: 8px;
            }
          }
          .setting-group-item-btn {
            padding: 0 12px;
            display: flex;
            align-items: center;
            gap: 12px;
          }
        }
      }
    }
    .setting-group-add {
      display: inline-flex;
      align-items: center;
      justify-content: flex-start;
      gap: 8px;
      color: #2590ff;
      cursor: pointer;
    }
  }
}

.color-select {
  height: 180px;
  overflow-y: auto;
  margin-bottom: 20px;
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
  .color-list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding-bottom: 12px;
    .color-item {
      cursor: pointer;
      border-radius: 4px;
      display: inline-block;
      font-size: 12px;
      font-weight: 400;
      padding: 2px 8px;
    }
  }
}

.color-select-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-left: 12px;
  .color-item {
    width: 16px;
    height: 16px;
    margin-right: 16px;
    border-radius: 50%;
    cursor: pointer;
    text-align: center;
    line-height: 16px;
  }
}

.iconDef {
  cursor: pointer;
}
</style>

<style lang="less">
.ant-tabs-dropdown-menu-item-remove {
  display: none;
}
.ant-tabs-dropdown-menu-item {
  min-width: 0;
  padding: 5px 20px;
}

.cusomt-moadl {
  position: relative;
  .ant-modal-body {
    padding: 0;
  }
  .hz-btn-group {
    padding: 0 20px 20px 20px;
  }
  .add-tag-btn {
    position: absolute;
    bottom: 20px;
    left: 20px;
  }
}
</style>
